const express = require('express');
const path = require('path');
const XLSX = require('xlsx');
const app = express();
const port = 3100;


app.use(express.static('public'));
app.use(express.static(__dirname));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));


function readExcelData() {
    try {
        const workbook = XLSX.readFile(path.join(__dirname, 'data/lottery.xlsx'));
        
     
        const nameSheet = workbook.Sheets['抽奖名单'];
        const participants = XLSX.utils.sheet_to_json(nameSheet);
        
      
        const ruleSheet = workbook.Sheets['抽奖规则'];
        const rules = XLSX.utils.sheet_to_json(ruleSheet);
        
        return { participants, rules };
    } catch (error) {
        console.error('读取Excel文件出错:', error);
        return { participants: [], rules: [] };
    }
}


app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'bootstrap.html'));
});


app.get('/api/data', (req, res) => {
    const data = readExcelData();
    res.json(data);
});


app.post('/api/draw', (req, res) => {
    const { award, count } = req.body;
    const { participants } = readExcelData();
    
    const availableParticipants = participants.filter(p => !p.winner);
    

    const winners = [];
    for (let i = 0; i < count && availableParticipants.length > 0; i++) {
        const randomIndex = Math.floor(Math.random() * availableParticipants.length);
        const winner = availableParticipants.splice(randomIndex, 1)[0];
        winner.award = award;
        winner.winner = true;
        winners.push(winner);
    }
    
    res.json({ success: true, winners });
});


app.post('/api/reset', (req, res) => {
    const workbook = XLSX.readFile(path.join(__dirname, 'data/lottery.xlsx'));
    const nameSheet = workbook.Sheets['抽奖名单'];
    const participants = XLSX.utils.sheet_to_json(nameSheet);
    

    participants.forEach(p => {
        delete p.winner;
        delete p.award;
    });
    

    const newSheet = XLSX.utils.json_to_sheet(participants);
    workbook.Sheets['抽奖名单'] = newSheet;
    XLSX.writeFile(workbook, path.join(__dirname, 'data/lottery.xlsx'));
    
    res.json({ success: true });
});

app.listen(port, () => {
    console.log(`抽奖程序运行在 http://localhost:${port}`);
});